﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Data.Linq.SqlClient;

namespace BLL
{
    public class FinaceRecordBll
    {

        public void Test()
        {
            //var c =from a in DB.PersonalFinanceDB.PayRecord select a;

            //int i=0;
        }


        /**/
        /// <summary>
        /// 同类型数据赋值
        /// </summary>
        /// <param name="DataSetter">需要设置值的对象</param>
        /// <param name="DataGetter">值来源</param> 
        /// <param name="IsLinqData">是否为linq模式</param>
        public static void SameValueCopier(object DataSetter, object DataGetter, bool IsLinqData)
        {

            PropertyInfo[] propertyInfoList = DataSetter.GetType().GetProperties();
            foreach (PropertyInfo propertyInfo in propertyInfoList)
            {
                if (propertyInfo.MemberType == MemberTypes.Property)
                {
                    string propertyName = propertyInfo.Name;

                    PropertyInfo info = DataGetter.GetType().GetProperty(propertyName);
                    object value = null;

                    if (info != null)
                    {
                        value = info.GetValue(DataGetter, null);
                    }

                    if (IsLinqData)
                    {
                        if (!propertyInfo.PropertyType.IsGenericType)
                        {
                            DataSetter.GetType().GetProperty(propertyName).SetValue(DataSetter, value, null);
                        }
                    }
                    else
                    {
                        if (DataSetter.GetType().GetProperty(propertyName) != null)
                        {
                            DataSetter.GetType().GetProperty(propertyName).SetValue(DataSetter, value, null);
                        }
                    }

                }
            }
        }

        public void AddFinaceRecord(FinaceRecord model)
        {
            FinaceTypeBll typeBll = new FinaceTypeBll();
            FinaceType typeModel = typeBll.SelectSingleFinaceType((int)model.FinaceTypeID);

            model.RecordTime = DateTime.Now;
            model.IsPayOut = typeModel.IDLink.StartsWith(FinaceTypeIDLink.PayOut);

            DB.PersonalFinanceDB.FinaceRecord.InsertOnSubmit(model);
            DB.PersonalFinanceDB.SubmitChanges();
        }

        public void UpdateFinaceRecord(FinaceRecord model)
        {
            /*
             *  发现更好的解决方法 
查询方法时 :context.ObjectTrackingEnabled = false; 
其他: context.ObjectTrackingEnabled = true
             */
            FinaceRecord record = DB.PersonalFinanceDB.FinaceRecord.Single(a => a.FinaceRecordID == model.FinaceRecordID);
            SameValueCopier(record, model, false);

            DB.PersonalFinanceDB.SubmitChanges();
        }

        public void DelFinaceRecord(int recordID)
        {
            FinaceRecord model = (from a in DB.PersonalFinanceDB.FinaceRecord where a.FinaceRecordID == recordID select a).Single();

            DB.PersonalFinanceDB.FinaceRecord.DeleteOnSubmit(model);
            DB.PersonalFinanceDB.SubmitChanges();
        }

        public FinaceRecord SelectSingleFinaceRecord(int recordID)
        {
            FinaceRecord finaceRecord = DB.PersonalFinanceDB.FinaceRecord.Where(a => a.FinaceRecordID == recordID)
                                                                 .Single()
                                                                 ;

            return finaceRecord;
        }


        private SqlCommand BuidSelectFinacePar(QueryFinaceRecordPar entity)
        {
            SqlCommand cmd = new SqlCommand();

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "SelectFinaceRecord";

            List<SqlParameter> lstPar = new List<SqlParameter>();

            SqlParameter par = new SqlParameter("@MemberID", entity.MemberID);
            lstPar.Add(par);

            par = new SqlParameter("@ParentPayTypeID", entity.ParentPayTypeID);
            lstPar.Add(par);

            par = new SqlParameter("@PayTimeStart", entity.FinaceTimeStart);
            lstPar.Add(par);

            par = new SqlParameter("@PayTimeEnd",  entity.FinaceTimeEnd.AddDays(1.0));
            lstPar.Add(par);

            par = new SqlParameter("@Amount", entity.Amount);
            lstPar.Add(par);

            par = new SqlParameter("@AmountOperator", entity.AmountOperator);
            lstPar.Add(par);

            par = new SqlParameter("@Detail", entity.Detail);
            lstPar.Add(par);

            par = new SqlParameter("@PageIndex", entity.PageIndex);
            lstPar.Add(par);

            par = new SqlParameter("@PageSize", entity.PageSize);
            lstPar.Add(par);

            cmd.Parameters.AddRange(lstPar.ToArray());

            return cmd;
        }

        /// <summary>
        ///  查询财务记录
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public DataTable SelectFinaceRecord( QueryFinaceRecordPar entity,out int rowCount )
        {
            entity.IsSumRowCounts = false;

            SqlCommand cmd = this.BuidSelectFinacePar(entity);

            using (SqlConnection cn = new SqlConnection(DB.ConStr))
            {
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                cmd.Connection = cn;

                DataSet ds = new DataSet();
                da.Fill(ds);

                rowCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);

                return ds.Tables[0];
            }
        }

        public  AnalyzeFinaceRecordResult AnalyzeFinaceRecord(QueryFinaceRecordPar entity,int mainFinaceType)
        {
            return DB.PersonalFinanceDB.AnalyzeFinaceRecord(entity.MemberID, entity.ParentPayTypeID, entity.FinaceTimeStart, entity.FinaceTimeEnd.AddDays(1.0),
                                                     entity.Amount, entity.AmountOperator, entity.Detail,mainFinaceType).Single();
        }
    
    }
}
